package com.crane.common.web.controller;


import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.crane.common.core.dto.SingleResponse;
import com.crane.common.core.exception.AppException;
import com.crane.common.core.exception.BasicErrorCode;
import com.crane.common.core.exception.BizException;
import com.crane.common.core.utils.StringUtil;
import com.crane.oss.common.bean.request.AddDynamicCodeRequest;
import com.crane.oss.common.bean.request.AuthCodeRequest;
import com.crane.oss.common.bean.request.GetForgetPwdCodeRequest;
import com.crane.oss.common.bean.request.LoginCodeRequest;
import com.crane.oss.common.bean.request.SendSMSRequest;
import com.crane.oss.common.bean.request.VerifyCodeRequest;
import com.crane.oss.common.bean.resp.SendSMSResp;
import com.crane.oss.sys.bean.resp.UserBean;
import com.crane.oss.enums.DynamicCodeTypeEnum;
import com.crane.oss.common.service.SmsSendRecordService;
import com.crane.oss.properties.SmsConfigProperties;
import com.crane.oss.common.service.AliyunSMSService;
import com.crane.oss.common.service.DynamicCodeService;
import com.crane.oss.sys.service.UserService;
import com.crane.oss.web.BaseBusinessController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

/**
 * @author bealon
 * @email ccsu123456@qq.com
 * @date 2019年01月08日 19时38分36秒
 */

@SuppressWarnings("rawtypes")
@Api(value = "DynamicCodeController", tags = {"验证码接口"})
@RestController
@RequestMapping("/api/dynamiccode")
public class DynamicCodeController extends BaseBusinessController {

    private final String MSG_PREFIX = "验证码已发送到手机：";
    @Autowired
    private DynamicCodeService dynamicCodeService;
    @Autowired
    private UserService userService;

    @Resource
    protected SmsConfigProperties dbkjConfigProperties;

    @Autowired
    private AliyunSMSService aliyunSMSService;
    @Autowired
    private SmsConfigProperties smsConfigProperties;
    @Autowired
    private SmsSendRecordService smsSendRecordService;

	@ApiOperation(value = "获取登录短信验证码", notes = "获取登录短信验证码")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "LoginCodeRequest")
    @PostMapping("/loginCode")
    public SingleResponse loginCode(@RequestBody @Valid LoginCodeRequest request) {
        UserBean userBean = userService.queryUserByName(request.getUserName());
        if (userBean == null) {
            throw new AppException(BasicErrorCode.ENTITY_NOT_EXISTS, "用户");
        }
        // 创建并发送登录验证码
        AddDynamicCodeRequest addDynamicCodeRequest = new AddDynamicCodeRequest();
        addDynamicCodeRequest.setUserId(userBean.getUserName());
        addDynamicCodeRequest.setPhone(userBean.getMobile());
        addDynamicCodeRequest.setBizType(DynamicCodeTypeEnum.LOGIN_CODE.getValue());
        addDynamicCodeRequest.setMemo(DynamicCodeTypeEnum.LOGIN_CODE.getRemark());
        String dynamicCode = dynamicCodeService.getCode(addDynamicCodeRequest, null);

        this.sendSms(dynamicCode, userBean.getMobile(), userBean.getRealName());

        return SingleResponse.of(MSG_PREFIX + StringUtil.mark(userBean.getMobile(), '*', 3, 7));

    }

    @ApiOperation(value = "获取实名认证短信验证码", notes = "获取实名认证短信验证码")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "AuthCodeRequest")
    @PostMapping("/authCode")
    public SingleResponse authCode(@RequestBody @Valid AuthCodeRequest request) {
        // 创建并发送验证码
        AddDynamicCodeRequest authCodeRequest = new AddDynamicCodeRequest();
        authCodeRequest.setUserId(null);
        authCodeRequest.setPhone(request.getReservePhone());
        authCodeRequest.setBizType(DynamicCodeTypeEnum.AUTH_CODE.getValue());
        authCodeRequest.setMemo(DynamicCodeTypeEnum.AUTH_CODE.getRemark());
        dynamicCodeService.getCode(authCodeRequest, null);
        return SingleResponse.of(MSG_PREFIX + StringUtil.mark(request.getReservePhone(), '*', 3, 7));
    }

    @ApiOperation(value = "获取通用短信验证码", notes = "获取通用短信验证码")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "VerifyCodeRequest")
    @PostMapping("/generate")
    public SingleResponse genVerifycode(@RequestBody @Valid VerifyCodeRequest request) {
        // 创建并发送验证码
        AddDynamicCodeRequest addDynamicCodeRequest = new AddDynamicCodeRequest();
        addDynamicCodeRequest.setUserId(null);
        addDynamicCodeRequest.setPhone(request.getPhone());
        addDynamicCodeRequest.setBizType(DynamicCodeTypeEnum.VERIFY_CODE.getValue());
        addDynamicCodeRequest.setMemo(DynamicCodeTypeEnum.VERIFY_CODE.getRemark());
        dynamicCodeService.getCode(addDynamicCodeRequest, null);
        return SingleResponse.of(MSG_PREFIX + StringUtil.mark(request.getPhone(), '*', 3, 7));
    }

    @ApiOperation(value = "获取忘记密码验证码", notes = "获取忘记密码验证码")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataType = "GetForgetPwdCodeRequest")
    @PostMapping("/forgetPwd")
    public SingleResponse forgetPassWord(@RequestBody @Valid GetForgetPwdCodeRequest request) {
        UserBean userBean = userService.queryUserByName(request.getUserName());
        // 验证接受手机号码
        if (!userBean.getMobile().equals(request.getPhone())) {
            throw new BizException("手机号码错误");
        }
        // 查询列表数据
        AddDynamicCodeRequest addDynamicCodeRequest = new AddDynamicCodeRequest();
        addDynamicCodeRequest.setUserId(userBean.getUserName());
        addDynamicCodeRequest.setPhone(request.getPhone());
        addDynamicCodeRequest.setBizType(DynamicCodeTypeEnum.FORGET_PASSWORD.getValue());
        addDynamicCodeRequest.setMemo(DynamicCodeTypeEnum.FORGET_PASSWORD.getRemark());
        String dynamicCode =  dynamicCodeService.getCode(addDynamicCodeRequest, null);
        if (dbkjConfigProperties.isSmsOpenFlag()) {
            this.sendSms(dynamicCode, userBean.getMobile(), userBean.getRealName());
        }
        return SingleResponse.of(MSG_PREFIX + StringUtil.mark(request.getPhone(), '*', 3, 7));
    }

    private void sendSms(String dynamicCode, String phone, String name) {
        SendSMSRequest sendRequest = new SendSMSRequest();
        sendRequest.setMsgTypeNo(smsConfigProperties.getVerifyCodeTemplate());
        sendRequest.setCode(dynamicCode);
        sendRequest.setPhoneNumber(phone);
        sendRequest.setName(name);
        SendSMSResp sendResp = aliyunSMSService.sendSms(sendRequest);
        smsSendRecordService.save(sendResp);
    }

}
